package org.paboo.http;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.paboo.util.LoggerFactoryUtils;

/**
 * Servlet implementation class BaseServlet
 */
public abstract class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = -5906978589632886533L;
	private LoggerFactoryUtils logger = LoggerFactoryUtils.getInstance().load(getClass());
	protected String defaultCharacterEncoding;
    
    public void init(ServletConfig config) throws ServletException {
    	super.init(config);
		defaultCharacterEncoding = getServletConfig().getInitParameter("default-character-encoding");
	}
    
    protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method)
			throws ServletException, IOException;

    protected String getParameterWithDefault(HttpServletRequest request,
			String name, String defaultStr) {
		String str = request.getParameter(name) == null ? defaultStr : request
				.getParameter(name);
		logger.info("Request parameter " + name + " is " + str);
		return str;
	}

    protected Integer getIntParameterWithDefault(HttpServletRequest request,
			String name, int defaultV) throws NumberFormatException {
		String str = getParameterWithDefault(request, name, defaultV + "");
		if (Pattern.compile("^[0-9]+$").matcher(str).matches()) {
			return Integer.parseInt(str);
		} else {
			throw new NumberFormatException("Request data is not number.");
		}
	}

	protected void sendErrorMsg(HttpServletResponse response, String errorMsg) throws IOException {
		logger.error(errorMsg);
		response.setContentType("text/plain");
		response.getOutputStream().print(errorMsg);
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response, HttpMethod.valueOf(request.getMethod()));
		} catch (ServletException | IOException e) {
			logger.error(e);
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "SERVER EXCEPTION!!!");
		}
	}

}
